package xyz.cerberu.cet.global.utils;

import org.apache.shiro.codec.Base64;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * @author β世界
 * Created on 11:18
 * @Description AES加密工具
 */
public class AESUtils {
    private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String KEY_ALGORITHM = "AES";

    /**
     * @author β世界 on 11:27 2021/3/30
     * 进行aes编码
     * @param str: 需要被加密的字符串
     * @param key: 密钥
     * @return java.lang.String
     **/
    public static String encode(String str,final String key){
        String result = null;
        try {
            // 创建编码器和初始化编码器
            Cipher encodeCipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            encodeCipher.init(Cipher.ENCRYPT_MODE,getSecretKeySpec(key));
            // 进行编码
            byte[] data = encodeCipher.doFinal(str.getBytes());
            result = Base64.encodeToString(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @author β世界 on 12:43 2021/3/30
     * 进行AES的解密
     * @param str: 加密后的字符串
     * @param key: 密钥
     * @return java.lang.String
     **/
    public static String decode(String str,final String key){
        String result = null;
        try {
            // 创建编码器和初始化编码器
            Cipher decodeCipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
            decodeCipher.init(Cipher.DECRYPT_MODE,getSecretKeySpec(key));
            // 进行编码
            byte[] data = decodeCipher.doFinal(Base64.decode(str.getBytes()));
            result = new String(data,StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static Key getSecretKeySpec(final String key) throws NoSuchAlgorithmException {
        KeyGenerator kg = null;
        kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG" );
        secureRandom.setSeed(key.getBytes(StandardCharsets.UTF_8));
        kg.init(128, secureRandom);
        SecretKey secretKey = kg.generateKey();
        return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
    }

}
